<!DOCTYPE html>
<html lang="zh" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="book">
<meta name="generator" content="Paradox, paradox-material-theme=0.6.0, mkdocs-material=3.0.3">

<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="">
<meta name="lang:search.pipeline.stopwords" content="true">
<meta name="lang:search.pipeline.trimmer" content="true">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">


<meta name="description" content="book">
<link rel="shortcut icon" href="../assets/images/favicon.png">
<title>PathDirectives（路径指令） · Scala Web 开发——基于Akka HTTP</title>
<link rel="stylesheet" href="../assets/stylesheets/application.451f80e5.css">
<link rel="stylesheet" href="../assets/stylesheets/application-palette.22915126.css">
<meta name="theme-color" content="#009688" />
<link rel="stylesheet" href="../lib/material__tabs/dist/mdc.tabs.min.css">
<link rel="stylesheet" href="../lib/prettify/prettify.css">
<script src="../assets/javascripts/modernizr.1aa3b519.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700|Roboto+Mono">
<style>
body,input{font-family:"Roboto","Helvetica Neue",Helvetica,Arial,sans-serif}
code,kbd,pre{font-family:"Roboto Mono","Courier New",Courier,monospace}
</style>
<link rel="stylesheet" href="../assets/fonts/font-awesome.css">
<link rel="stylesheet" href="../assets/fonts/material-icons.css">
<link rel="stylesheet" href="../assets/stylesheets/paradox-material-theme.css">
</head>
<body
data-md-color-primary="teal"
data-md-color-accent="indigo"
>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="Scala Web 开发——基于Akka HTTP" class="md-header-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">
Scala Web 开发——基于Akka HTTP
</span>
<span class="md-header-nav__topic">
PathDirectives（路径指令）
</span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">&#xE5CD;</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>

</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/yangbajing/scala-web-development"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
yangbajing/scala-web-development
</div>
</a>

</div>
</div>
</div>
</nav>
</header>

<div class="md-container">
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0" style="visibility: hidden">
<label class="md-nav__title md-nav__title--site" for="drawer">
<a href="../index.html" title="Scala Web 开发——基于Akka HTTP" class="md-nav__button md-logo">
<span class="md-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
<a href="../index.html" title="Scala Web 开发——基于Akka HTTP">
Scala Web 开发——基于Akka HTTP
</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/yangbajing/scala-web-development"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
yangbajing/scala-web-development
</div>
</a>

</div>
<ul>
  <li><a href="../preface.html" class="page">前言</a></li>
  <li><a href="../env/index.html" class="page">Scala 环境配置</a>
  <ul>
    <li><a href="../env/env.1.html" class="page">Sbt</a></li>
    <li><a href="../env/env.2.html" class="page">IDE开发工具</a></li>
    <li><a href="../env/env.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../scala/index.html" class="page">Scala 语言基础</a>
  <ul>
    <li><a href="../scala/scala.0.html" class="page">REPL</a></li>
    <li><a href="../scala/scala.1.html" class="page">你好，Scala</a></li>
    <li><a href="../scala/scala.2.html" class="page">Scala基础</a></li>
    <li><a href="../scala/scala.3.html" class="page">流程和函数</a></li>
    <li><a href="../scala/scala.4.html" class="page">集合</a></li>
    <li><a href="../scala/scala.5.html" class="page">class和object</a></li>
    <li><a href="../scala/scala.6.html" class="page">函数式</a></li>
    <li><a href="../scala/scala.7.html" class="page">Trait</a></li>
    <li><a href="../scala/scala.8.html" class="page">并发</a></li>
    <li><a href="../scala/scala.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../basic/index.html" class="page">Akka HTTP 基础</a>
  <ul>
    <li><a href="../basic/basic.0.html" class="page">Akka HTTP 基础</a></li>
    <li><a href="../basic/basic.1.html" class="page">Web 工作方式</a></li>
    <li><a href="../basic/basic.2.html" class="page">使用 Akka Http 搭建一个简单的 Web 服务</a></li>
    <li><a href="../basic/basic.3.html" class="page">Akka HTTP 的通用抽象</a></li>
    <li><a href="../basic/basic.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../server-api/index.html" class="page">服务端API</a>
  <ul>
    <li><a href="../server-api/work.html" class="page">Akka HTTP 如何使得 Web 工作</a></li>
    <li><a href="../server-api/advanced.html" class="page">高级服务端 API</a></li>
  </ul></li>
  <li><a href="../routing-dsl/index.html" class="page">路由DSL</a>
  <ul>
    <li><a href="../routing-dsl/route.html" class="page">Route 路由</a></li>
    <li><a href="../routing-dsl/directive.html" class="page">Directive 指令</a></li>
    <li><a href="../routing-dsl/custom-directive.html" class="page">自定义指令</a></li>
    <li><a href="../routing-dsl/rejections.html" class="page">拒绝 rejections</a></li>
    <li><a href="../routing-dsl/exception.html" class="page">异常处理</a></li>
    <li><a href="../routing-dsl/file-upload.html" class="page">实战：大文件断点上传、下载和秒传</a></li>
  </ul></li>
  <li><a href="../directives/index.html" class="page">常用指令</a>
  <ul>
    <li><a href="../directives/path.html" class="active page">PathDirectives（路径指令）</a></li>
    <li><a href="../directives/method.html" class="page">directives/method.html</a></li>
    <li><a href="../directives/parameter_form.html" class="page">directives/parameter_form.html</a></li>
    <li><a href="../directives/marshalling.html" class="page">directives/marshalling.html</a></li>
    <li><a href="../directives/file.html" class="page">directives/file.html</a></li>
    <li><a href="../directives/cookie.html" class="page">directives/cookie.html</a></li>
  </ul></li>
  <li><a href="../data/index.html" class="page">数据</a>
  <ul>
    <li><a href="../data/data.0.html" class="page">数据</a></li>
    <li><a href="../data/data.1.html" class="page">JSON</a></li>
    <li><a href="../data/data.ant-design-pro.html" class="page">实战：为Ant Design Pro提供后端接口</a></li>
    <li><a href="../data/data.kryo.html" class="page">Kryo</a></li>
    <li><a href="../data/data.2.html" class="page">Protobuf</a></li>
    <li><a href="../data/data.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../test/index.html" class="page">测试</a>
  <ul>
    <li><a href="../test/test.0.html" class="page">测试</a></li>
    <li><a href="../test/test.1.html" class="page">Scalatest</a></li>
    <li><a href="../test/test.2.html" class="page">测试异步代码</a></li>
    <li><a href="../test/test.3.html" class="page">端到端测试Route</a></li>
    <li><a href="../test/test.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../actor/index.html" class="page">Akka Actor</a>
  <ul>
    <li><a href="../actor/actor.html" class="page">Akka Typed Actor</a></li>
    <li><a href="../actor/actor-test.html" class="page">Akka Actor 测试</a></li>
    <li><a href="../actor/actor.z.html" class="page">Actor小结</a></li>
  </ul></li>
  <li><a href="../oauth/index.html" class="page">实战：实现OAuth 2服务</a>
  <ul>
    <li><a href="../oauth/oauth.0.html" class="page">实战：OAuth 2 服务</a></li>
    <li><a href="../oauth/oauth.1.html" class="page">OAuth 2简介</a></li>
    <li><a href="../oauth/oauth.2.html" class="page">OAuth 2接口设计</a></li>
    <li><a href="../oauth/oauth.3.html" class="page">OAuth 2服务实现</a></li>
    <li><a href="../oauth/oauth.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../database/index.html" class="page">访问数据库</a>
  <ul>
    <li><a href="../database/database.0.html" class="page">访问数据库</a></li>
    <li><a href="../database/database.1.html" class="page">使用 JDBC 访问 PostgreSQL</a></li>
    <li><a href="../database/database.2.html" class="page">使用 Slick 访问数据库</a></li>
    <li><a href="../database/database.3.html" class="page">访问 Cassandra 数据库</a></li>
    <li><a href="../database/database.4.html" class="page">访问 Redis</a></li>
    <li><a href="../database/database.5.html" class="page">访问 Elasticsearch</a></li>
    <li><a href="../database/database.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../engineering/index.html" class="page">工程化</a>
  <ul>
    <li><a href="../engineering/swagger.html" class="page">使用Swagger编写API文档</a></li>
    <li><a href="../engineering/guice.html" class="page">使用Guice管理类依赖</a></li>
  </ul></li>
  <li><a href="../grpc/index.html" class="page">Akka gRPC</a>
  <ul>
    <li><a href="../grpc/grpc.html" class="page">gRPC服务</a></li>
    <li><a href="../grpc/build-tool.html" class="page">构建工具</a></li>
    <li><a href="../grpc/deployment.html" class="page">部署</a></li>
    <li><a href="../grpc/grpc.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../config-discovery/index.html" class="page">实战：配置管理、服务发现系统</a></li>
  <li><a href="../appendix/index.html" class="page">附录</a>
  <ul>
    <li><a href="../appendix/appendix.0.html" class="page">参考资料</a></li>
    <li><a href="../appendix/appendix.1.html" class="page">专业术语</a></li>
    <li><a href="../appendix/appendix.2.html" class="page">词汇表</a></li>
  </ul></li>
  <li><a href="../donate.html" class="page">赞助</a></li>
</ul>
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../directives/path.html#pathdirectives-路径指令-" class="header">PathDirectives（路径指令）</a>
  <ul>
    <li><a href="../directives/path.html#path示例" class="header">Path示例</a></li>
    <li><a href="../directives/path.html#深入uri-path" class="header">深入<code>Uri.Path</code></a></li>
    <li><a href="../directives/path.html#深入pathmatcher" class="header">深入<code>PathMatcher</code></a></li>
  </ul></li>
</ul>
</nav>

</nav>
<ul style="display: none">
<li class="md-nav__item md-version" id="project.version">
<label class="md-nav__link" for="__version">
<i class="md-icon" title="Version">label_outline</i> 1.0.0
</label>
</li>
</ul>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../directives/path.html#pathdirectives-路径指令-" class="header">PathDirectives（路径指令）</a>
  <ul>
    <li><a href="../directives/path.html#path示例" class="header">Path示例</a></li>
    <li><a href="../directives/path.html#深入uri-path" class="header">深入<code>Uri.Path</code></a></li>
    <li><a href="../directives/path.html#深入pathmatcher" class="header">深入<code>PathMatcher</code></a></li>
  </ul></li>
</ul>
</nav>

</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset">
<div class="md-content__searchable">
<h1><a href="#pathdirectives-路径指令-" name="pathdirectives-路径指令-" class="anchor"><span class="anchor-link"></span></a>PathDirectives（路径指令）</h1>
<p>以指定的路径与<code>RequestContext.unmatchedPath</code>进行匹配，当匹配成功时可选提取一个或多个值（提取值的类型由指定的路径参数决定）。若匹配失败，将调用<code>reject</code>拒绝此次请求。它处理的类型为：<code>Uri.Path</code>（之后简称<code>Path</code>）。</p>
<p><em>官方文档：<a href="https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/path-directives/index.html">https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/path-directives/index.html</a></em></p>
<p>最常会用到的路径指令有：<code>pathPrefix</code>、<code>path</code>、<code>pathEnd</code>和<code>pathEndOrSingleSlash</code>。</p>
<p><code>pathPrefix</code>：对于路径：<code>/user/page</code>，指令<code>pathPrefix(&quot;user&quot;)</code>将先与第一个&rsquo;/&rsquo;匹配，再匹配<code>user</code>，然后将剩余部分<code>/page</code>设置到<code>RequestContext.unmatchedPath</code>。<code>pathPrefix(X)</code>只与路径的前缀部分匹配<code>X</code>。</p>
<p><code>path</code>：对于路径：<code>/page</code>，指令<code>path(&quot;page&quot;)</code>将先与&rsquo;/&rsquo;匹配，再匹配<code>page</code>，同时剩余部分应为空，它将<code>RequestContext.unmatchedPath</code>设置为<code>Path.Empty</code>。<code>path(X)</code>会与路径进行完整匹配。</p>
<p><code>pathEnd</code>：<code>pathEnd</code>是一个没有参数的指令，将在剩余路径为<code>Path.Empty</code>时匹配成功。它常用于在嵌套路由下匹配父路由已经完全匹配的路径（<code>unmatchedPath</code>为<code>Path.Empty</code>）。</p>
<p><code>pathEndOrSingleSlash</code>：类似<code>pathEnd</code>，但它还会在剩余路径为<code>Slash</code>（路径为&rsquo;/&rsquo;）时也匹配成功。</p><div class="callout note "><div class="callout-title">注意</div>
<p>对于希望只匹配URI的一部分，而将剩余部分委托给嵌套路由（子路由）时必需使用<code>pathPrefix</code>指令。只有当确定嵌套部分不再对URI进行匹配操作时才使用<code>path</code>指令。因此，将一个<code>path</code>或<code>path</code>指令嵌套在一个<code>path</code>指令下，它是永远不会被匹配上的。因为这时候<code>RequestContext.unmatchedPath</code>为空。</p></div>
<h2><a href="#path示例" name="path示例" class="anchor"><span class="anchor-link"></span></a>Path示例</h2>
<pre class="prettyprint"><code class="language-scala">// 路由：
val route =
  path(&quot;foo&quot;) {
    complete(&quot;/foo&quot;)
  } ~
    path(&quot;foo&quot; / &quot;bar&quot;) {
      complete(&quot;/foo/bar&quot;)
    } ~
    pathPrefix(&quot;ball&quot;) {
      pathEnd {
        complete(&quot;/ball&quot;)
      } ~
        path(IntNumber) { int =&gt;
          complete(if (int % 2 == 0) &quot;even ball&quot; else &quot;odd ball&quot;)
        }
    }

// 测试：
Get(&quot;/&quot;) ~&gt; route ~&gt; check {
  handled shouldEqual false
}

Get(&quot;/foo&quot;) ~&gt; route ~&gt; check {
  responseAs[String] shouldEqual &quot;/foo&quot;
}

Get(&quot;/foo/bar&quot;) ~&gt; route ~&gt; check {
  responseAs[String] shouldEqual &quot;/foo/bar&quot;
}

Get(&quot;/ball/1337&quot;) ~&gt; route ~&gt; check {
  responseAs[String] shouldEqual &quot;odd ball&quot;
}
</code></pre>
<h2><a href="#深入uri-path" name="深入uri-path" class="anchor"><span class="anchor-link"></span></a>深入<code>Uri.Path</code></h2>
<p><code>Uri.Path</code>是一个递归数据结构，类似Scala集合类型<code>List</code>，它的简化版定义如下：</p>
<pre class="prettyprint"><code class="language-scala">  sealed abstract class Path {
    type Head // head的类型由实现类定义，可能是`Char`，也可能是`String`
    def isEmpty: Boolean
    def startsWithSlash: Boolean
    def startsWithSegment: Boolean
    def endsWithSlash: Boolean
    def head: Head // 路径链表头
    def tail: Path // 路径链表剩余部分
    def length: Int // 整个路径链表长度，包括解码字符和路径段
    def charCount: Int // 整个路径链里解码字符的数量
    def ::(c: Char): Path = { require(c == &#39;/&#39;); Path.Slash(this) }
    def ::(segment: String): Path
    def +(pathString: String): Path = this ++ Path(pathString)
    def ++(suffix: Path): Path
    def /(segment: String): Path = this ++ Path.Slash(segment :: Path.Empty)
    def ?/(segment: String): Path = if (this.endsWithSlash) this + segment else this / segment
    def dropChars(count: Int): Path // 从链表头部开始，去看count个解码字符，同时解码字符间的路径段也一起被去掉
  }
</code></pre><div class="callout note "><div class="callout-title">名词解释</div>
<ul>
  <li><strong>解码字符</strong>：URI通过&rsquo;/&lsquo;符合分隔，路径需要使用&rsquo;/&rsquo;都需要对其进行encode。在Akka HTTP里抽象为<code>Slash</code>类型。</li>
  <li><strong>路径段</strong>：URI字符串是被解码字符分隔出来的字符串。在Akka HTTP里抽象为<code>Segment</code>类型。</li>
</ul></div>
<p><code>Path</code>定义为抽象类，它的具体实现类有三个：<code>Empty</code>、<code>Slash</code>、<code>Segment</code>，而<code>Empty</code>继承于<code>SlashOrEmpty</code>。</p>
<ul>
  <li>
  <p><strong>SlashOrEmpty</strong>：路径为解码字符&rsquo;/&rsquo;或空</p>
  <pre class="prettyprint"><code class="language-scala">sealed abstract class SlashOrEmpty extends Path {
  def startsWithSegment = false
}
</code></pre></li>
  <li>
  <p><strong>Empty</strong>：路径为空</p>
  <pre class="prettyprint"><code class="language-scala">case object Empty extends SlashOrEmpty {
  type Head = Nothing
  def isEmpty = true
  def startsWithSlash = false
  def head: Head = throw new NoSuchElementException(&quot;head of empty path&quot;)
  def tail: Path = throw new UnsupportedOperationException(&quot;tail of empty path&quot;)
}
</code></pre></li>
  <li>
  <p><strong>Slash</strong>：路径为解码字符&rsquo;/&rsquo;</p>
  <pre class="prettyprint"><code class="language-scala">final case class Slash(tail: Path) extends SlashOrEmpty {
  type Head = Char
  def head = &#39;/&#39;
}
</code></pre></li>
  <li>
  <p><strong>Segment</strong>：路径为字符串，URI里面实际的路径段。</p>
  <pre class="prettyprint"><code class="language-scala">final case class Segment(head: String, tail: SlashOrEmpty) extends Path {
  if (head.isEmpty) throw new IllegalArgumentException(&quot;Path segment should not be empty&quot;)
  type Head = String
}
</code></pre></li>
</ul>
<h2><a href="#深入pathmatcher" name="深入pathmatcher" class="anchor"><span class="anchor-link"></span></a>深入<code>PathMatcher</code></h2>
<p>当一个HTTP请求（若确切地说一个<code>RequestContext</code>实例）进行路由结构时，它有一个与<code>request.uri.path</code>相同类型的<code>unmatchedPath</code>。当<code>RequestContext</code>通过路由树向下传播，通过一个或多个<code>pathPrefix</code>或者<code>path</code>路径时，<code>unmatchedPath</code>的左边被逐渐“吃掉”。</p>
<p>在每个指令中，都由路径匹配DSL来精确地进行匹配并从中提取需要的内容。路径匹配DSL围绕着以下类型构建：</p>
<pre class="prettyprint"><code class="language-scala">trait PathMatcher[L: Tuple]
type PathMatcher0 = PathMatcher[Unit]
type PathMatcher1[T] = PathMatcher[Tuple1[T]]
type PathMatcher2[T,U] = PathMatcher[Tuple2[T,U]]
// .. 等等
</code></pre>
<p><code>PathMatcher</code>的实例对<code>unmatchedPath</code>进行精确的匹配和提取值，提取值的数量和类型由泛型参数<code>L</code>表示，<code>L</code>需要是Scala的<code>Tuple</code>或<code>Unit</code>类型之五（由<code>Tuple</code>上下文绑定限定）。</p>
<p>看一个较复杂的例子：</p>
<pre class="prettyprint"><code class="language-Scala">val matcher: PathMatcher1[Option[Int]] =
  &quot;foo&quot; / &quot;bar&quot; / &quot;X&quot; ~ IntNumber.? / (&quot;edit&quot; | &quot;create&quot;)
</code></pre>
<p><code>matcher</code>将匹配<code>/foo/bar/X32/edit</code>或者<code>/foo/bar/X/create</code>。<code>&quot;X&quot; ~ IntNumber.?</code>的意思是匹配一个<code>X</code>字符加0个或多个十进制整数字符，同时所有整数字符全在一起数值取值范围为**int32**。</p><div class="callout note "><div class="callout-title">注意</div>
<p>路径匹配DSL在匹配URI路径以后才对已匹配部分进行解码。这意味着路径分隔符不能写到字符串中，必需使用<code>/</code>函数来定义，不然字符串<code>&quot;foo/bar&quot;</code>将匹配原始的字符串<code>&quot;foo%2fbar&quot;</code>，这应该不是你想要的。</p></div>
<h3><a href="#常用基本的pathmatcher" name="常用基本的pathmatcher" class="anchor"><span class="anchor-link"></span></a>常用基本的<code>PathMatcher</code></h3>
<p>一个路径匹配器可以通过组合或修改多个基本的<code>PathMatcher</code>来构造，以下是常用的基本<code>PathMatcher</code>。</p>
<p><strong>字符串</strong></p>
<p><code>String</code>的实例可以作为<code>PathMatcher0</code>。字符串只匹配自身，不提取任何值。需要注意的是字符串被解释为路径的解码表示（decode），当它包含一个&rsquo;/&lsquo;字符时，这个字符将与编码的原始URI中的&rsquo;%2f&rsquo;进行匹配。</p>
<p><strong>正则表达式</strong></p>
<p><code>Regex</code>的实例可以作为<code>PathMatcher1[String]</code>。正则表达式不包含捕获组时将提取完整匹配或者只包含一个捕获组时提取捕获的内容，若正则表达式包含多个捕获组，则将引发<code>IllegalArgumentException</code>异常。</p>
<p><strong><code>Segment: PathMatcher1[String]</code></strong></p>
<p>从路径段不以&rsquo;/&rsquo;斜线开始匹配，将匹配的部分提取为字符串。</p>
<p><strong><code>IntNumber: PathMatcher1[Int]</code></strong></p>
<p>匹配一个或多个十进制字符为非负的<code>Int</code>数值。</p>
<p><strong><code>LongNumber: PathMatcher1[Long]</code></strong></p>
<p>匹配一个或多个十进制字符为非负的<code>Long</code>数值。</p>
<h3><a href="#组合子-combinators-" name="组合子-combinators-" class="anchor"><span class="anchor-link"></span></a>组合子（Combinators）</h3>
<p>Path的路径匹配器（Matcher）可以组合起来形成更高级的结构。</p>
<p><strong><code>~</code> 操作符</strong></p>
<p><code>~</code>操作符可以将两个Matcher指令连接起来。它将两个Matcher连接成一个，同时还保持Matcher的类型安全。如：<code>&quot;foo&quot; ~ &quot;bar&quot;</code> 等价于 <code>&quot;foobar&quot;</code>。</p>
<p><strong><code>/</code> 操作符</strong></p>
<p><code>/</code>操作符连接两个Matcher，并在中间插入 <strong>Slash（<code>/</code>）</strong> 匹配器。如：<code>&quot;foo&quot; / &quot;bar&quot;</code> 等价于 <code>&quot;foo&quot; ~ Slash ~ &quot;bar&quot;</code>。</p>
<p><strong><code>|</code> 操作符</strong></p>
<p><code>|</code>操作符组合了两个Matcher的方案，当且第一个不匹配时才尝试第二个，且两个Matcher必须具有兼容的类型。如：<code>(&quot;foo&quot; | &quot;bar&quot;) / &quot;bom&quot;</code>将先匹配<code>/foo/bom</code>路由，再匹配<code>/bar/bom</code>路由（&lsquo;/&rsquo;的优先级比&rsquo;|&rsquo;高，所以这里需要使用小括号括起来）。</p>
<h3><a href="#修饰符" name="修饰符" class="anchor"><span class="anchor-link"></span></a>修饰符</h3>
<p>&lsquo;/&rsquo;和&rsquo;?&rsquo;可作为修饰符作用于Matcher上，如下所示：</p>
<pre class="prettyprint"><code class="language-scala">// 匹配 /foo/
path(&quot;foo&quot;./)

// 匹配 /foo/bar
path(&quot;foo&quot; / &quot;bar&quot;)

// 注意: 匹配 /foo%2Fbar 而不是 /foo/bar
path(&quot;foo/bar&quot;)

// 匹配 /foo/bar
path(separateOnSlashes(&quot;foo/bar&quot;))

// 匹配 /foo/123 等 并抽取 &quot;123&quot; 作为字符串类型的抽取值
path(&quot;foo&quot; / &quot;&quot;&quot;\d+&quot;&quot;&quot;.r)

// 匹配 /foo/bar123 并抽取 &quot;123&quot; 作为字符串类型的抽取值
path(&quot;foo&quot; / &quot;&quot;&quot;bar(\d+)&quot;&quot;&quot;.r)

// 类似 `path(Segments)`
path(Segment.repeat(10, separator = Slash))

// 匹配 /i42 等 或者 /hCAFE 等，并抽取值为Int类型
path(&quot;i&quot; ~ IntNumber | &quot;h&quot; ~ HexIntNumber)

// 等价于 path(&quot;foo&quot; ~ (PathEnd | Slash))
path(&quot;foo&quot; ~ Slash.?)

// 匹配 /red 或 /green 或 /blue 并分别抽取 1, 2 或 3
path(Map(&quot;red&quot; -&gt; 1, &quot;green&quot; -&gt; 2, &quot;blue&quot; -&gt; 3))

// 匹配任何以 /foo 开头且不以 /foobar 开头的路径
pathPrefix(&quot;foo&quot; ~ !&quot;bar&quot;)
</code></pre>
</div>
<div>
<a href="https://github.com/yangbajing/scala-web-development/tree/master/book/src/main/paradox/directives/path.md" title="Edit this page" class="md-source-file md-edit">
Edit this page
</a>
</div>
<div class="print-only">
<span class="md-source-file md-version">
1.0.0
</span>
</div>
</article>
</div>
</div>
</main>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="../directives/index.html" title="常用指令" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Previous
</span>
常用指令
</span>
</div>
</a>
<a href="../directives/method.html" title="" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Next
</span>
</span>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
Powered by
<a href="https://github.com/lightbend/paradox">Paradox</a>
and
<a href="https://jonas.github.io/paradox-material-theme/">Paradox Material Theme</a>

</div>
<div class="md-footer-social">
<a href="https://github.com/yangbajing" class="md-footer-social__link fa fa-github"></a><a href="https://weibo.com/yangbajing" class="md-footer-social__link fa fa-globe"></a><a href="https://www.yangbajing.me/" class="md-footer-social__link fa fa-globe"></a>
</div>

</div>
</div>
</footer>

</div>
<script src="../assets/javascripts/application.583bbe55.js"></script>
<script src="../assets/javascripts/paradox-material-theme.js"></script>
<script>app.initialize({version:"0.17",url:{base:"../."}})</script>
<script type="text/javascript" src="../lib/prettify/prettify.js"></script>
<script type="text/javascript" src="../lib/prettify/lang-scala.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
window.prettyPrint && prettyPrint();
});
</script>
</body>
</html>
